package com.example.myapplication.dialog

import android.app.Dialog
import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.example.myapplication.R
import kotlinx.android.synthetic.main.dialog_opertion.*

/**
 *操作的弹窗
 *
 * @author : Kun
 * @date : 2021/6/8
 * @time : 14:27
 */
class OperationDialog(context: Context) : Dialog(context) {
    private var operationAdapter: OperationAdapter
    private var list = ArrayList<String>()

    private var onSelectListener: OnSelectListener? = null

    init {
        setContentView(R.layout.dialog_opertion)
        operationAdapter = OperationAdapter(R.layout.item_opertion, list)
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.adapter = operationAdapter
        operationAdapter.setOnItemClickListener { _, _, position ->
            onSelectListener?.onSelect(list.get(position), position)
        }
        setCanceledOnTouchOutside(true)
        setCancelable(true)


        val windowManager = window!!.windowManager

        val lp = this.window!!.attributes
        // Dialog宽度
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
            lp.width = (windowManager.currentWindowMetrics.bounds.width() * 0.76).toInt()
        } else {
            lp.width = (windowManager.defaultDisplay.width * 0.76).toInt()
        }
        val window = window
        window!!.attributes = lp
        window.decorView.background.alpha = 0
    }

    /**
     * 增加一个操作
     */
    fun addSelectItem(item: String) {
        list.add(item)
        operationAdapter.notifyDataSetChanged()
    }

    /**
     * 增加一个选项
     */
    fun addSelectItems(vararg items: String) {
        for (item in items) {
            list.add(item)
        }
        operationAdapter.notifyDataSetChanged()
    }

    /**
     * 清空操作
     */
    fun clearOperation() {
        list.clear()
        operationAdapter.notifyDataSetChanged()
    }

    /**
     * 设置监听
     */
    fun setOnSelectListener(listener: OnSelectListener) {
        onSelectListener = listener

    }

    interface OnSelectListener {
        fun onSelect(name: String, position: Int)
    }

    class OperationAdapter(layoutResId: Int, mList: ArrayList<String>?) :
        BaseQuickAdapter<String, BaseViewHolder>(layoutResId, mList) {
        override fun convert(holder: BaseViewHolder, item: String) {
            holder.setText(R.id.tv_title, item)
        }
    }
}